<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['id'])) {
        throw new Exception('缺少ID参数');
    }

    // 读取 books.json
    $booksFile = __DIR__ . '/../../data/books.json';
    if (!file_exists($booksFile)) {
        throw new Exception('书籍数据文件不存在');
    }

    $books = json_decode(file_get_contents($booksFile), true);
    if (!isset($books['books'])) {
        throw new Exception('数据格式错误');
    }

    // 更新书籍内容
    $updated = false;
    foreach ($books['books'] as &$book) {
        if ($book['id'] == $data['id']) {
            if (isset($data['title'])) {
                $book['title'] = $data['title'];
            }
            if (isset($data['content'])) {
                $book['content'] = $data['content'];
                error_log("Saving content for book {$data['id']}: " . substr($data['content'], 0, 100) . "...");
            }
            
            // 根据contentImages数组计算总页数
            $imageCount = isset($data['contentImages']) ? count($data['contentImages']) : 0;
            $book['imageCount'] = $imageCount;
            
            $updated = true;
            break;
        }
    }

    if (!$updated) {
        throw new Exception('未找到指定的书籍');
    }

    // 保存回文件
    $jsonData = json_encode($books, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    if ($jsonData === false) {
        throw new Exception('JSON编码失败: ' . json_last_error_msg());
    }

    if (!file_put_contents($booksFile, $jsonData)) {
        throw new Exception('保存文件失败');
    }

    error_log("Book {$data['id']} saved successfully");

    echo json_encode([
        'success' => true,
        'message' => '保存成功'
    ]);

} catch (Exception $e) {
    error_log('Save Error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?> 